package UpdateData

import (
	"FromNowOnPromote/博客系统/Tblog/controllers"
	"FromNowOnPromote/博客系统/Tblog/models"
	"FromNowOnPromote/博客系统/Tblog/models/User"
	"FromNowOnPromote/博客系统/Tblog/redis"
	"encoding/json"
	"log"
	"strconv"
	"time"
)

type UpdateUser struct {
	controllers.MainController
}
type Response struct {
	Username  string
	Sex       string
	Introduce string
	Email     string
	Birthday  string
	Address   string
}

func (this *UpdateUser) Post() {
	//验证token
	token := this.Ctx.GetCookie("uuid")
	rd := redis.R.Conn
	defer rd.Close()
	id, err := rd.Get(token)
	id_int, _ := strconv.Atoi(id)
	body := map[string]interface{}{"code": "300", "msg": "非法请求"}
	if err != nil {
		log.Fatal("用户不存在")
	} else {
		resp := this.Ctx.Request.Body
		decoder := json.NewDecoder(resp)
		var r Response
		err := decoder.Decode(&r)
		if err != nil {
			body = map[string]interface{}{"code": "301", "msg": "请求参数不正确"}
		} else {
			user := User.TbUser{}
			db := models.ConnDb()
			model := db.Model(&user)
			defer db.Close()
			birthday, err := time.Parse("2006-01-02", r.Birthday)
			if err != nil {
				log.Fatal(err)
				panic(err)
			}
			e := model.Where("Uuid=?", id_int).Updates(map[string]interface{}{"Username": r.Username, "Sex": r.Sex,
				"Introduction": r.Introduce, "Address": r.Address, "Email": r.Email, "Birthday": birthday}).Error
			if e != nil {
				log.Fatal(e)
			}
			body = map[string]interface{}{"code": "200", "msg": "修改成功"}
		}

	}

	this.Data["json"] = body
	this.ServeJSON()
}
